#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "log.hpp"
enum
{
    SocketErr = 2,
    BindErr,
    ListenErr,
};
const int backlog = 10;
class Sock
{
public:
    Sock()
    {
    }
    ~Sock()
    {
    }

public:
    // 封装套接字接口
    void Socket() // 创建套接字
    {
        sockfd_ = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd_ < 0)
        {
            lg(Fatal, "socker error,%s:%d", strerror(errno), errno);
            exit(SocketErr);
        }
        int opt=1;
        //处理time_wait状态，允许地址复用
        setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    }
    void Bind(uint16_t port) // 绑定接口，更新内核数据
    {
        struct sockaddr_in local; // 存储本地服务端信息结构体
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;//选择协议簇
        local.sin_port = htons(port);
        local.sin_addr.s_addr=INADDR_ANY;
        if (bind(sockfd_, (struct sockaddr *)&local, sizeof(local)) < 0) // 核心代码
        {
            lg(Fatal, "bind error,%s:%d", strerror(errno), errno);
            exit(BindErr);
        }
    }
    void Listen() // 监听客户端发来的链接请求
    {
        if (listen(sockfd_, backlog) < 0)
        {
            lg(Fatal, "listen error,%s:%d", strerror(errno), errno);
            exit(ListenErr);
        }
    }
    int Accept(std::string *clientip, uint16_t *clientport) // 接受客户端发来的请求
    {
        struct sockaddr_in peer; // 存储客户端信息
        socklen_t len = sizeof(peer);
        int newfd = accept(sockfd_, (struct sockaddr *)&peer, &len); // 核心
        if (newfd < 0)
        {
            lg(Warning, "accept error,%s:%d", strerror(errno), errno);
            return -1;
        }
        char ipstr[64];
        inet_ntop(AF_INET, &peer.sin_addr, ipstr, sizeof(ipstr));//获取客户端的IP地址
        *clientip = ipstr;
        *clientport = ntohs(peer.sin_port);
        return newfd;
    }
    //连接
    bool Connect(const std::string &ip, const uint16_t &port)
    {
        struct sockaddr_in peer; // 存储目标信息体
        memset(&peer, 0, sizeof(peer));
        peer.sin_family = AF_INET;//选择协议簇
        peer.sin_port = htons(port);//主机转网络序列
        inet_pton(AF_INET, ip.c_str(), &(peer.sin_addr));//获取服务端IP地址
        int n = connect(sockfd_, (struct sockaddr *)&peer, sizeof(peer));//利用存储的服务端结构体和服务端建立连接
        if (n == -1) // 连接失败
        {
            std::cerr << "connecr to " << ip << ": " << port << "error" << std::endl;
            return false;
        }

        return true;
    }
    void Close()
    {
        close(sockfd_);
    }
    int Fd()
    {
        return sockfd_;
    }

private:
    int sockfd_;
};
